
/*
    对图片加载进行一次封装，现在使用 Kingfisher
*/

import Foundation
import UIKit
import Kingfisher


public extension UIImageView {
    //原始图
    func setImageWithURLString(_ URLString: String?, placeholderImage placeholder: UIImage? = nil) {
        guard let URLString = URLString, let URL = URL(string: URLString) else {
            printLog("URL wrong")
            return
        }
        self.kf.setImage(with: URL)
    }
    
    /**
     圆角图
     */
    func setCircularImageWithURLString(_ URLString: String?, placeholderImage placeholder: UIImage? = nil) {
        self.setRoundImageWithURLString(
            URLString,
            placeholderImage: placeholder,
            cornerRadiusRatio: self.width / 2
        )
    }
    
    /**
     设置 cornerRadiusRatio
     */
    func setCornerRadiusImageWithURLString(
        _ URLString: String?,
        placeholderImage placeholder: UIImage? = nil ,
        cornerRadiusRatio: CGFloat? = nil)
    {
        self.setRoundImageWithURLString(
            URLString,
            placeholderImage: placeholder,
            cornerRadiusRatio: cornerRadiusRatio
        )
    }
    
    func setRoundImageWithURLString(
        _ URLString: String?,
        placeholderImage placeholder: UIImage? = nil ,
        cornerRadiusRatio: CGFloat? = nil,
        progressBlock: ImageDownloaderProgressBlock? = nil)
    {
        guard let URLString = URLString, let URL = URL(string: URLString) else {
            printLog("URL wrong")
            return
        }
        
        let memoryImage = KingfisherManager.shared.cache.retrieveImageInMemoryCache(forKey:URLString)
        let diskImage = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey:URLString)
        guard let image = memoryImage ?? diskImage else {
            let optionInfo: KingfisherOptionsInfo = [
                .forceRefresh,
            ]
            KingfisherManager.shared.downloader.downloadImage(with: URL, options: optionInfo, progressBlock: progressBlock) { (image, error, imageURL, originalData) -> () in
                if let image = image, let originalData = originalData {
                    DispatchQueue.global(qos: .default).async {
                        let roundedImage = image.roundWithCornerRadius(image.size.width * (cornerRadiusRatio ?? 0.5))
                        KingfisherManager.shared.cache.store(roundedImage, original: originalData, forKey: URLString, toDisk: true, completionHandler: {
                            self.setImageWithURLString(URLString)
                        })
                    }
                }
            }
            return
        }
        self.image = image
    }
}







